package com.sgb.capital.viewmodel;

import android.app.Application;
import android.text.SpannableString;
import android.view.Gravity;

import com.sgb.capital.api.CapitalManager;
import com.sgb.capital.callback.AbstractOnClickPopListener;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.model.BaseEntity;
import com.sgb.capital.model.InvoiceApplyBean;
import com.sgb.capital.model.InvoiceCompanyInfoBean;
import com.sgb.capital.model.UserAddressBean;
import com.sgb.capital.utils.CapitalLog;
import com.sgb.capital.utils.DialogHelper;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableField;
import androidx.lifecycle.AndroidViewModel;
import razerdp.basepopup.BasePopupSDK;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 开票列表
 * 弹窗样式：与IOS一致从底部弹出
 * @author cyj
 */
public class ConfirmInvoiceModel extends AndroidViewModel {

    /** 发票状态信息已发生变化 */
    private final String FLAG_INVOICE_STATUS_CHANGED = "E0000001";
    /** 传递数据：开票金额 */
    public ObservableField<SpannableString> invoiceTotalMoney = new ObservableField<>();
    /** 传递数据：开票流水id数组 */
    public String[] ids = new String[0];
    /** 发票内容，2021-07-23 目前只有这一种 */
    public ObservableField<String> invoiceContent = new ObservableField<>("交易手续费");


    /** 是否选择了个人开票类型 */
    public ObservableBoolean hasCheckedPersonal = new ObservableBoolean(false);
    /** 是否选择了企业公司开票类型，默认企业公司开票类型 */
    public ObservableBoolean hasCheckedCompany = new ObservableBoolean(true);
    /** 是否显示个人，如果发票选择的专业，那么隐藏个人选项 */
    public ObservableBoolean hasNoShowPersonal = new ObservableBoolean(false);
    /** 开票类型数组 */
    public String[] allInvoiceTypeList = {"增值税普通发票(纸质)", "增值税专用发票(纸质)"};
    /** 当前发票类型 */
    public ObservableField<String> invoiceType = new ObservableField<>(allInvoiceTypeList[0]);
    /** 个人时，输入的发票抬头内容 */
    public ObservableField<String> personalInvoiceName = new ObservableField<>("");


    /** 发票公司信息列表部分 发票公司信息列表 */
    public Map<String, String> companyNameMap = new LinkedHashMap<>();
    /** 选择的企业单位信息，绑定UI自动刷新 */
    public ObservableField<Long> companyNameInfoItemId = new ObservableField<>(-1L);
    public ObservableField<InvoiceCompanyInfoBean> invoiceCompanyInfoBean = new ObservableField<>(new InvoiceCompanyInfoBean());
    /** 是否显示公司信息布局视图 */
    public ObservableBoolean isShowCompanyInfoView = new ObservableBoolean(false);
    /** 是否显示公司信息中的除税号外的信息；这里企业选中的是普通发票，那么只显示税号 */
    public ObservableBoolean isShowCompanyOtherInfoView = new ObservableBoolean(false);


    /** 收件人列表部分 收件人列表 */
    public Map<String, String> addresseeMap = new LinkedHashMap<>();
    /** 用户地址管理信息对象（包含收件人信息列表） */
    public ObservableField<UserAddressBean> userAddressBean = new ObservableField<>(new UserAddressBean());
    /** 是否显示收件人信息布局视图 */
    public ObservableBoolean isShowAddresseeView = new ObservableBoolean(false);
    /** 选择的收件人信息，绑定UI自动刷新 */
    public ObservableField<Long> addresseeItemId = new ObservableField<>(-1L);


    public ConfirmInvoiceModel(@NonNull Application application) {
        super(application);
        // 默认
        invoiceType.set(allInvoiceTypeList[0]);
    }

    /** 网络获取开票信息公司信息 */
    public void getInvoiceCompanyInfoList() {
        DialogHelper.showProgressDialog(BasePopupSDK.getInstance().getTopActivity(),"数据加载中").setCanceledOnTouchOutside(false);
        CapitalManager.getInstance().getCapitalAPI().getInvoiceCompanyInfoList().enqueue(new Callback<BaseEntity<InvoiceCompanyInfoBean>>() {

            @Override
            public void onResponse(Call<BaseEntity<InvoiceCompanyInfoBean>> call, Response<BaseEntity<InvoiceCompanyInfoBean>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(CapitalManager.RESPONSE_OK)) {
                    invoiceCompanyInfoBean.set(response.body().getData());
                    companyNameMap.clear();
                    companyNameMap.putAll(response.body().getData().convertUIShowData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<InvoiceCompanyInfoBean>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                CapitalLog.e("ERROR", t.getMessage());
            }
        });
    }

    /** (CheckBox点击事件)选中个人开票类型 */
    public void cbxClickForPersonalInvoice() {
        hasCheckedCompany.set(false);
        invoiceType.set(allInvoiceTypeList[0]);
    }

    /** (CheckBox点击事件)选中企业公司开票类型 */
    public void cbxClickForCompanyInvoice() {
        hasCheckedPersonal.set(false);
    }

    /** 网络获取收件人列表信息，判断是否含有收件人列表信息并提示引导用户前往PC端新增收件人信息 */
    public void getAddresseeList() {
        CapitalManager.getInstance().getCapitalAPI().queryUserAddress().enqueue(new Callback<BaseEntity<List<UserAddressBean.Records>>>() {

            @Override
            public void onResponse(Call<BaseEntity<List<UserAddressBean.Records>>> call, Response<BaseEntity<List<UserAddressBean.Records>>> response) {
                if (response.body().getState().equals(CapitalManager.RESPONSE_OK)) {
                    userAddressBean.set(new UserAddressBean().setData(response.body().getData()));
                    addresseeMap.clear();
                    addresseeMap.putAll(userAddressBean.get().convertUIShowData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<UserAddressBean.Records>>> call, Throwable t) {
                CapitalLog.e("ERROR", t.getMessage());
            }
        });
    }

    /** 获取发票申请数据对象 */
    private InvoiceApplyBean getInvoiceApplyBean() throws NullPointerException {
        InvoiceApplyBean bean = new InvoiceApplyBean();
        bean.ids = this.ids;
        bean.makeBy = hasCheckedCompany.get() ? 1 : 2;
        bean.invoiceType = Objects.equals(invoiceType.get(), allInvoiceTypeList[1]) ? 1 : 2;
        bean.invoiceContent = invoiceContent.get();
        // 单位信息
        if(hasCheckedCompany.get()) {
            InvoiceCompanyInfoBean.InvoiceCompanyList companyInfo = invoiceCompanyInfoBean.get().getItem(companyNameInfoItemId.get());
            bean.invoiceHead = companyInfo.companyName;
            bean.companyDutyNo = companyInfo.creditCode;
            bean.companyBankName = companyInfo.bank;
            bean.companyBankAccount = companyInfo.bankAccount;
            bean.companyPhone = companyInfo.phone;
            bean.companyAddress = companyInfo.address;
        } else if(hasCheckedPersonal.get()) {
            bean.invoiceHead = personalInvoiceName.get();
        }
        // 收件人信息
        UserAddressBean.Records userAddressRecordsInfo = userAddressBean.get().getItem(addresseeItemId.get());
        bean.mailName = userAddressRecordsInfo.consigneeName;
        bean.mailPhone = userAddressRecordsInfo.phone;
        bean.mailAreaName = userAddressRecordsInfo.getAreaDesc();
        bean.mailAddress = userAddressRecordsInfo.address;

        return bean;
    }

    /** 检查申请开票信息用户是否填写完整 */
    private boolean checkInvoiceApplyInfo() {
        boolean check = false;
        if(hasCheckedPersonal.get()) {
            check = personalInvoiceName.get().length() <= 0 || addresseeItemId.get() < 0;
        } else if(hasCheckedCompany.get()) {
            check = companyNameInfoItemId.get() < 0 || addresseeItemId.get() < 0;
        }
        if(check) {
            // 单位信息 || 收件人信息 未填入
            MToast.showLongToast(getApplication().getApplicationContext(), "请确保信息完整后再进行提交", Gravity.CENTER);
            return false;
        }
        return true;
    }

    /** (button点击事件)索取发票 */
    public void btnClickForGetInvoice() {
        if(!checkInvoiceApplyInfo()) {
            return;
        }
        DialogHelper.showProgressDialog(BasePopupSDK.getInstance().getTopActivity(),"数据加载中").setCanceledOnTouchOutside(false);
        CapitalManager.getInstance().getCapitalAPI().invoiceApply(getInvoiceApplyBean()).enqueue(new Callback<BaseEntity>() {

            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body().getState().equals(CapitalManager.RESPONSE_OK)) {
                    showCancelPop("您已成功提交开票申请，平台将于2至5个工作日内完成审核", 1);
                } else if(FLAG_INVOICE_STATUS_CHANGED.equals(response.body().getCode())) {
                    showCancelPop("发票状态信息已发生变化", 2);
                } else {
                    MToast.showLongToast(getApplication().getApplicationContext(), response.body().getMsg(), Gravity.CENTER);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(getApplication(), t.getMessage());
            }
        });
    }

    /** 显示关闭弹窗并实现关闭时的点击事件 */
    private void showCancelPop(String content, int type) {
        new TipPop(getApplication(), "温馨提示", content, null, "知道了", new AbstractOnClickPopListener() {
            @Override
            public void onClickCancel() {
                if(1 == type) {
                    Utils.sendMsg(Constants.EVENT_CONFIRM_INVOICE_JUMP_ASIA_RECORD, null);
                    BasePopupSDK.getInstance().getTopActivity().finish();
                } else if(2 == type) {
                    BasePopupSDK.getInstance().getTopActivity().finish();
                }
            }
        }).show();
    }
}